//quit the ballbet system
var docLeague = "";
var intervalID;

function toOpenWindowByType(inType, uri) {
  var winopts = "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar";
  openWindowByType(inType, uri, winopts);
  //window.open(uri, "_blank", winopts);
}

function startVenkman() {
  start_venkman();
}

function quitSystem() {
  //window.close();
  quit(Ci.nsIAppStartup.eForceQuit);
}

//restart the system
function restartSystem() {
  quit(Ci.nsIAppStartup.eForceQuit | Ci.nsIAppStartup.eRestart);
}

function quit(quitparam) {
  var appStartup = Cc['@mozilla.org/toolkit/app-startup;1'].getService(Ci.nsIAppStartup);
  appStartup.quit(quitparam);
}

function systemSetting() {
  window.openDialog("chrome://ballbet/content/ballbetoptions.xul", "系统设置", "", null);
}

function nameSetting() {
  window.open("chrome://ballbet/content/namesetting.xul", "namesetting", "modal, resizable");
}

function saveName() {

}

//get the information frome the bet sites
function getInfo() {
  macauLive = null;
  macauLeagueLive = null;

  getInfos();  
  
  var timeInterval = getIntegerPreference("getinfo.interval", false);
  intervalID = window.setInterval("getInfos();", timeInterval);
  //测试更新网站，更新数据已经可以了
  var refreshInterval = getIntegerPreference("refreshdata.interval", false);
  //jsdump("refreshInterval: " + refreshInterval);
  window.setInterval("refreshMacauData();", refreshInterval);
  window.setInterval("refreshLijiData();", refreshInterval);
  window.setInterval("refreshShabaData();", refreshInterval);
  window.setInterval("refreshNewballData();", refreshInterval);
  
}

/*
    停止自动获取信息
*/
function stopGetInfo() {
  if (intervalID != undefined) {
    window.clearInterval(intervalID);
  }
}

//找到同名的联盟信息
function findLeagueNames() {
  var leagueRoot = domLeagues.getElementsByTagName("Leagues")[0];
  var leagues = leagueRoot.getElementsByTagName("League");
//  jsdump("leagues:" + leagues.length);

  var leagueSameNames = [];
  for (var i = 0; i < macauLeagueLive; i++) {
    for (var j = 0; j < leagues.length; j++) {
      var strings = leagues[j].textContent.split('=');
      if (strings[0] == macauLeagues[i].name) {
        leagueSameNames.push(leagues[j].textContent);
        break;
      }
    }
  }
  return leagueSameNames;
}

//找到同名的球队信息
function findTeamNames() {
  var teamRoot = domTeams.getElementsByTagName("Teams")[0];
  var teams = teamRoot.getElementsByTagName("Team");
//  jsdump("teams:" + teams.length);

  var teamSameNames = [];
  for (var i = 0; i < macauLive; i++) {
    for (var j = 0; j < teams.length; j++) {
      var strings = teams[j].textContent.split('=');
      //一场比赛里面有两支球队进行比赛
      if ((strings[0] == macauTransOrder[i].homeTeam) ||
          (strings[0] == macauTransOrder[i].awayTeam)) {
        teamSameNames.push(teams[j].textContent);
        //jsdump("teams[j].textContent: " + teams[j].textContent + "; =" + j + "; i=" + i + "; macauTransOrder[i][1]: " + macauTransOrder[i][1] + "; macauTransOrder[i][2]: " + macauTransOrder[i][2]);
        //如果是偶数
        if (teamSameNames.length == (i + 1) * 2) {
          //jsdump("findTeamNames: length:" + teamSameNames.length);
          break;
        }
        continue;
      }
    }
  }
  return teamSameNames;
}

/*
    根据获取的信息把让球盘的信息对应起来，并找到满足投注的比赛                                                                    
*/
function getOrderInfos(leagueSameNames, teamSameNames, macauOrder, lijiOrder, shabaOrder, newballOrder, type) {
  var curLevelInfos = [];
  for (var i = 0; i < macauLive; i++) {
    var macautrans = macauOrder[i];
    var findLeague = false;
    var findFirstTeam = false;
    var findSecTeam = false;
    var leagueNames = '';
    var firstTeams = '';
    var secTeams = '';
    var levelSub = -0.01; //总的水位差
    var awayWeb = {level:'', levelID:'', name:'', levelPos:0};
    var macauGate = '';
    for (var j = 0; j < leagueSameNames.length; j++) {
      //jsdump("leagueSameNames[j]：" + leagueSameNames[j] + "; macautrans[0]" + macautrans[0]);
      if (leagueSameNames[j].split('=').find(macautrans.leagueName) ) {
        leagueNames = leagueSameNames[j];
        findLeague = true;
        break;
      }
    }
        
    for (var j = 0; j < teamSameNames.length; j++) {
      //jsdump("j=" + j + "; teamSameNames[j]: " + teamSameNames[j] + "; macautrans[1]:" + macautrans[1]);
      if (teamSameNames[j].split('=').find(macautrans.homeTeam) ) {
        firstTeams = teamSameNames[j];
        findFirstTeam = true;
      }
      if (teamSameNames[j].split('=').find(macautrans.awayTeam) ) {
        secTeams = teamSameNames[j];
        findSecTeam = true;
      }
      if (findFirstTeam && findSecTeam) {
        break;
      }
    }

    //澳门网盘口
    var leftGates = macautrans.homeGates;
    var rightGates = macautrans.awayGates;
    //
    var gate1 = '';
    if (type == 'trans') {
      gate1 = calcBetGate(macautrans.homeScore, macautrans.awayScore, leftGates[0], rightGates[0]);
    } else if (leftGates[0] == rightGates[0]) {
      gate1 = leftGates[0];
    }
    var gate2 = '';
    macauGate = gate1;
    if (leftGates[1] != '') {
      if (type == 'trans') {
        gate2 = calcBetGate(macautrans.homeScore, macautrans.awayScore, leftGates[1], rightGates[1]);

      } else if (leftGates[1] == rightGates[1]) {
        gate2 = leftGates[1];
      }
      macauGate = gate1 + "-" + gate2;
      if(gate1>gate2)
        macauGate = gate2+"-"+gate1;
    } else {
      macauGate *= 1.0
    }
    macautrans.gate = macauGate;
    
    //找到了对应的联赛和球队，就在对应的副网里面找盘口对应的球队
    var lijiTrans = {homeLevel:'', awayLevel:'', pos:0, levelID:'', subLevel:-0.01, level:''};
    var shabaTrans = {homeLevel:'', awayLevel:'', pos:0, levelID:'', subLevel:-0.01, level:''};
    var newballTrans = {homeLevel:'', awayLevel:'', pos:0, levelID:'', subLevel:-0.01, level:''};
    if (findLeague && findFirstTeam && findSecTeam) {
      var leagues = leagueNames.split('=');
      var firTeams = firstTeams.split('=');
      var seTeams = secTeams.split('=');
      
      //满足下面的条件，就可以选择出来：
      //联盟-球队-盘口
      //利记网
      for (var j = 0; j < lijiOrder.length; j++) {        
        var findLea = leagues.find(lijiOrder[j].leagueName);
        var findFir = firTeams.find(lijiOrder[j].homeTeam);
        var findSe = seTeams.find(lijiOrder[j].awayTeam);
        if (findLea && findFir && findSe) {
          if (macauGate == lijiOrder[j].gate) {
            //计算赔率是否满足条件
            var first = calcLevel(macautrans.homeLevel, lijiOrder[j].awayLevel);
            var sec = calcLevel(macautrans.awayLevel, lijiOrder[j].homeLevel);
            lijiTrans.homeLevel = lijiOrder[j].homeLevel;
            lijiTrans.awayLevel = lijiOrder[j].awayLevel;
            if (first > sec && first >= 0) {
              lijiTrans.subLevel = first;
              lijiTrans.levelID = lijiOrder[j].awayLevelID;
              lijiTrans.pos = 0;
              lijiTrans.level = lijiOrder[j].awayLevel;
              
            } else if (first < sec && sec >= 0) {
              lijiTrans.subLevel = sec;
              lijiTrans.levelID = lijiOrder[j].homeLevelID;
              lijiTrans.pos = 1;
              lijiTrans.level = lijiOrder[j].homeLevel;
            }
            break;
          }
        }
      }

      //沙巴网
      for (var j = 0; j < shabaOrder.length; j++) {
        var findLea = leagues.find(shabaOrder[j].leagueName);
        var findFir = firTeams.find(shabaOrder[j].homeTeam);
        var findSe = seTeams.find(shabaOrder[j].awayTeam);
        if (findLea && findFir && findSe) {
          if (macauGate == shabaOrder[j].gate) {
            //计算赔率是否满足条件
            var first = calcLevel(macautrans.homeLevel, shabaOrder[j].awayLevel);
            var sec = calcLevel(macautrans.awayLevel, shabaOrder[j].homeLevel);
            shabaTrans.homeLevel = shabaOrder[j].homeLevel;
            shabaTrans.awayLevel = shabaOrder[j].awayLevel;
            if (first > sec && first >= 0) {
              shabaTrans.subLevel = first;
              shabaTrans.levelID = shabaOrder[j].awayLevelID;
              shabaTrans.pos = 0;
              shabaTrans.level = shabaOrder[j].awayLevel;
            } else if (first < sec && sec >= 0) {
              shabaTrans.subLevel = sec;
              shabaTrans.levelID = shabaOrder[j].homeLevelID;
              shabaTrans.pos = 1;
              shabaTrans.level = shabaOrder[j].homeLevel;
            }
            break;
          }
        }        
      }

      //新球网        
      for (var j = 0; j < newballOrder.length; j++) {
        var findLea = leagues.find(newballOrder[j].leagueName);
        var findFir = firTeams.find(newballOrder[j].homeTeam);      
        var findSe = seTeams.find(newballOrder[j].awayTeam);
        if (findLea && findFir && findSe) {
          if (macauGate == newballOrder[j].gate) {
            //计算赔率是否满足条件
            var first = calcLevel(macautrans.homeLevel, newballOrder[j].awayLevel);
            var sec = calcLevel(macautrans.awayLevel, newballOrder[j].homeLevel);
            newballTrans.homeLevel = newballOrder[j].homeLevel;
            newballTrans.awayLevel = newballOrder[j].awayLevel;
            if (first > sec && first >= 0) {
              newballTrans.subLevel = first;
              newballTrans.levelID = newballOrder[j].awayLevelID;
              newballTrans.pos = 0;
              newballTrans.level = newballOrder[j].awayLevel;
              
            } else if (first < sec && sec >= 0) {
              newballTrans.subLevel = sec;
              newballTrans.levelID = newballOrder[j].homeLevelID;
              newballTrans.pos = 1;
              newballTrans.level = newballOrder[j].homeLevel;
            }
            break;
          }
        }        
      }

      function asignAwayWeb(trans) {
        
      }
      //计算最后最大的赔率差
      //首先利记和沙巴比较，然后比较结果和新球网比较
      if (lijiTrans.subLevel >= 0 && lijiTrans.subLevel>= shabaTrans.subLevel) {
        levelSub = lijiTrans.subLevel;
        awayWeb.levelID = lijiTrans.levelID;
        awayWeb.levelPos = lijiTrans.pos;
        awayWeb.name = sites.liji;
        awayWeb.level = lijiTrans.level;

      } else if (shabaTrans.subLevel >= 0 && shabaTrans.subLevel >= newballTrans.subLevel) {
        levelSub = shabaTrans.subLevel;
        awayWeb.levelID = shabaTrans.levelID;
        awayWeb.levelPos = shabaTrans.pos;
        awayWeb.name = sites.shaba;
        awayWeb.level = shabaTrans.level;
        
      } else if (newballTrans.subLevel >= 0 && newballTrans.subLevel >= levelSub) {
        levelSub = newballTrans.subLevel;
        awayWeb.levelID = newballTrans.levelID;
        awayWeb.levelPos = newballTrans.pos;
        awayWeb.name = sites.newball;
        awayWeb.level = newballTrans.level;
      }

    }

    var levelInfo = new LevelInfo;
    levelInfo.awayWebName = awayWeb.name;
    levelInfo.homeTeam = macautrans.homeTeam;
    levelInfo.awayTeam = macautrans.awayTeam;
    levelInfo.gate = macauGate;
    levelInfo.levelSub = levelSub.toFixed(3);
    levelInfo.awayWebLevelID = awayWeb.levelID;
    levelInfo.awayWebLevel = awayWeb.level;
    levelInfo.levelPos = awayWeb.levelPos;
    levelInfo.lijiHomeLevel = lijiTrans.homeLevel;
    levelInfo.lijiAwayLevel = lijiTrans.awayLevel;
    levelInfo.shabaHomeLevel = shabaTrans.homeLevel;
    levelInfo.shabaAwayLevel = shabaTrans.awayLevel;
    levelInfo.newballHomeLevel = newballTrans.homeLevel;
    levelInfo.newballAwayLevel = newballTrans.awayLevel;
    levelInfo.homeWebLevelID = macautrans.homeLevelID;
    levelInfo.homeWebLevel = macautrans.homeLevel;
    if(levelInfo.levelPos == 1) {
      levelInfo.homeWebLevelID = macautrans.awayLevelID;
      levelInfo.homeWebLevel = macautrans.awayLevel;
    }
    //jsdump("getOrderInfos:"+type);
    //jsdump("homeWebLevelID: "+levelInfo.homeWebLevelID+"; homeWebLevel: "+levelInfo.homeWebLevel);
    curLevelInfos.push(levelInfo);    
  }
  return curLevelInfos;
}

/*
    获取最新的数据
*/
function getInfos() {
  macauLive = null;
  macauLeagueLive = null;

  getMacauInfo();
  getLijiInfo();
  getShabaInfo();
  getNewballInfo();

  //数据获取完成后，对数据进行处理，方便显示
  //首先要清空原来的显示数据，然后添加新的数据
  //让球盘数据
  //根据获取的信息和保存的同名列表，把联盟和球队同名的找出来
//  jsdump("findLeagueNames: ");
  var leagueSameNames = findLeagueNames();
//  jsdump("findTeamNames: ");
  var teamSameNames = findTeamNames();

  //清除上一次显示的投注信息
  clearListBetInfo();

  curTransLevelInfos = [];
  clearOrderShow("browser.transfer.order");
  createOrderTableRow("browser.transfer.order");

  curTransLevelInfos = getOrderInfos(leagueSameNames, teamSameNames, macauTransOrder, lijiTransOrder, shabaTransOrder, newballTransOrder, 'trans');
  setOrderShowInfo("browser.transfer.order", macauTransOrder, curTransLevelInfos, '让球盘');

  //大小盘数据
  curSizeLevelInfos = [];
  clearOrderShow("browser.size.order");
  createOrderTableRow("browser.size.order");
  curSizeLevelInfos = getOrderInfos(leagueSameNames, teamSameNames, macauSizeOrder, lijiSizeOrder, shabaSizeOrder, newballSizeOrder, 'size');
  setOrderShowInfo("browser.size.order", macauSizeOrder, curSizeLevelInfos, '大小盘');

}

// Trims leading and trailing spaces from a string
function trimString(str) {
  return str.replace(new RegExp("^\\s+|\\s+$", "gi"), "");
}

function openJsConsole(event) {
  openWindowByType("global:console", "chrome://global/content/console.xul");
}

/*
    澳门网的比分是通过图片名称来是别的，如果图片包含'dash'，就说明当前
    没有进行比赛，包赛数字就正在进行比赛。
*/
function getNumByImageName(imageName) {
  if (imageName.search('dash.gif') > -1) {
    return false;
  }
  var index1 = imageName.lastIndexOf('_');
  //alert(index1);
  var index2 = imageName.lastIndexOf('.');
  //alert(index2);
  var imgNum = imageName.substring(index1 + 1, index2);
  //alert(imgNum);
  return imgNum;
}

/*
    计算赔率公式:
    
*/
function calcLevel(levelA, levelB) {
  levelA *= 1;
  levelB *= 1;

  var ab = 0;
  if (levelA > 1.0 && levelB > 0) {
    ab = (levelA - 1) * levelB - 1;

  } else if (levelA > 1.0 && levelB < 0) {
    ab = levelA + levelB - 1;
  }
//  jsdump("levelA: " + levelA + "; levelB: " + levelB + "; result=" + ab);
  return ab;
}
/*
  计算盘口公式
  主网：比分：a:b(0:0, 1:0, 0:1, 1:1, 2:0, 0:2, 1:2, 2:1, 2:2)
  盘口：c:d(0:0, 1:-1, -1:1, 2:-2, -2:2, 3:-3)
  公式：e = c-(a-b); f=d+(a-b); g = e>=0:e?f;
  副网当前盘口：g	
*/
function calcBetGate(scoreA, scoreB, gateA, gateB) {
  var sub = scoreA * 1 - scoreB * 1;
  if (gateA * 1.0 >= 0 && sub >= 0) {
    return Math.abs(gateA * 1.0 - sub);
  } else if (gateA * 1.0 < 0 && sub > 0) {
    return Math.abs(gateA * 1.0 + sub);
  } else if (gateA * 1.0 >= 0 && sub <= 0) {
    return Math.abs(gateA * 1.0 + sub);
  } else if (gateA * 1.0 < 0 && sub <= 0) {
    return Math.abs(gateA * 1.0 - sub);
  }
  return 0;
  //var temA = gateA*1 - sub;
  //var temB = gateB*1 + sub;
  //jsdump("calcBetGate(scoreA, scoreB, gateA, gateB):" + scoreA +" "+ scoreB +" "+ gateA +" "+ gateB);
  //jsdump("temA:"+ temA + ": temB:"+temB);
  //if(temA >= 0) return temA;
  //else return temB; 
}

//整理盘口字符串
function calcGateString(gate) {
  gate = gate.replace('[', '');
  gate = gate.replace(']', '');
  gate = gate.replace('+', '');
  gate = gate.replace('+', '');
  var indexSlash = gate.indexOf('/');
  var gates = ['', ''];
  if (indexSlash > 0) {
    var gates = gate.split('/');
    var gate1 = trimString(gates[0]);
    var gate2 = trimString(gates[1]);
    gates[0] = gate1;
    gates[1] = gate2;
  } else {
    gates[0] = trimString(gate);
  }
//  jsdump("calcgate: gate: " + gate + "gates: " + gates[0] + ":" + gates[1]);
  return gates;
}

//找到盘口的ID号，原则是，保存下当前的属性和字符串，方便以后查找元素
function findLevelID(levelString) {
  //不提取信息，直接保存下来
  return levelString;
  //<span onclick="ot(5264784,-0.940,'h',1);" onmouseover="this.style.cursor='pointer';">-0.940</span>
  var first = levelString.indexOf('(');
  var second = levelString.indexOf(')');
  var id = levelString.substring(first + 1, second);
//  jsdump("findLevelID: ID: " + id);
  //alert(onclick.search(id));
  return id;
}

function findMacauLevelID(levelString) {
  //href="javascript:add_bir_bet('4590786','930','1000','4.0','Y','2','12','1|0')"
  var first = levelString.indexOf("\'");
  var second = levelString.indexOf("\'", first+1);
  var id = levelString.substring(first + 1, second);
  return id;
}

function findLijiLevelID(levelString) {
  //<span onclick="ot(13235364,0.980,'h',1);" onmouseover="this.style.cursor='pointer';">0.980</span>
  //<span onclick="ot(13235364,0.940,'a',1);" onmouseover="this.style.cursor='pointer';">0.940</span>
  var first = levelString.indexOf('\,');
  var second = levelString.indexOf('\,', first+1);
  var temp = levelString.substring(first + 1, second+1);
  var id = levelString.replace(temp, '');
  return id;
  
}

function findShabaLevelID(levelString) {
/*
  <a href="javascript:bet(0,'543608','4417550','h','-0.900')" class="FavOddsClass">-0.900</a>
  <a href="javascript:bet(0,'543608','4417550','a','0.820')" class="UdrDogOddsClass">0.820</a>
  <a href="javascript:bet(0,'543608','4417549','h','-0.980')" class="FavOddsClass">-0.980</a>
  <a href="javascript:bet(0,'543608','4417549','a','0.880')" class="UdrDogOddsClass">0.880</a>
*/
  var first = levelString.indexOf('\,');
  var end = levelString.lastIndexOf('\,');
  var id = levelString.substring(first+1, end);
  return id;
}

/*
    get macau datas
*/
function getMacauBodyData(tbody) {
  var typeInfos = tbody.getElementsByClassName("type_info");
  var leagaueLength = typeInfos.length;
//  jsdump("getMacauBodyData: started");
  if (leagaueLength <= 0) {
    alert("0");
    return;
  }

  //亚洲让球盘
  macauTransOrder = [];
  //大小盘
  macauSizeOrder = [];
  //联盟信息
  macauLeagues = [];

  var rows = tbody.rows;
  length = rows.length;
  var leagueIndex = -1; //联盟索引
  var footballIndex = -1; //标题栏索引，就是由多少个比赛的索引
  //get datas
  var i = -1;
  for (i = 0; i < length;) {
    var tr = rows[i];
    //表示联盟信息        
    var className = tr.className.trim();
    if (className == "type_info") {
      leagueIndex ++;
      var league = tr.getElementsByClassName("type_info")[0];
      var str = league.textContent.trim();      
      macauLeagues.push(new LeagueInfo(str));
      //jsdump("leagueIndex:"+leagueIndex+"; LeageuName: "+str);
      i++;
      continue;
      //表示球队信息
    } else if (className == "title_bir") {
      footballIndex++;
      macauTransOrder[footballIndex] = new OrderInfo();
      macauSizeOrder[footballIndex] = new OrderInfo();
      macauSizeOrder[footballIndex].leagueName = macauTransOrder[footballIndex].leagueName = macauLeagues[leagueIndex].name;
      
      var titles = tr.childNodes;
      var time1 = "";
      var time2 = "";
      var nodata = false;
      if (titles[3].childNodes.length == 1) {
        time1 = titles[3].textContent.trim();
      } else {
        time1 = titles[3].childNodes[0].textContent.trim();
        time2 = titles[3].childNodes[2].textContent.trim();
        nodata = true;
        if (macauLive == null && macauLeagueLive == null) {
          macauLive = footballIndex;
          macauLeagueLive = leagueIndex;
          //jsdump("macauLeagueLive:"+macauLeagueLive+"; macauLive:"+macauLive+
          //       "; macauLeagues.length: "+macauLeagues.length);
        }
      }
      var leftTeam = titles[5].textContent.trim();
      var rightTeam = titles[9].textContent.trim();
      var imgs = tr.getElementsByTagName("img");
      var leftScore = getNumByImageName(imgs[1].src);

      //如果当前没有进行比赛，那么返回false
      if (!leftScore) {
        leftScore = '';
      }
      var rightScore = getNumByImageName(imgs[3].src);  
      macauSizeOrder[footballIndex].homeTeam = macauTransOrder[footballIndex].homeTeam = leftTeam;
      macauSizeOrder[footballIndex].awayTeam = macauTransOrder[footballIndex].awayTeam = rightTeam;
      macauSizeOrder[footballIndex].time1 = macauTransOrder[footballIndex].time1 = time1;
      macauSizeOrder[footballIndex].time2 = macauTransOrder[footballIndex].time2 = time2;
      macauSizeOrder[footballIndex].homeScore = macauTransOrder[footballIndex].homeScore = leftScore;
      macauSizeOrder[footballIndex].awayScore = macauTransOrder[footballIndex].awayScore = rightScore;
      
      if (nodata) {
        macauSizeOrder[footballIndex].homeGates = macauTransOrder[footballIndex].homeGates = '';
      }

      i++;
      continue;
      //数据信息
    } else if ((className == "data_row") || (className == "data_row data_row_alt")) {
      var datas = tr.childNodes;
      var betName = datas[3].textContent.trim();
      var leftGate = datas[5].textContent.trim();
      var leftGates = calcGateString(leftGate);

      var rightGate = datas[11].textContent.trim();
      var rightGates = calcGateString(rightGate);

      var betLevels = tr.getElementsByTagName("a");
      var leftLevel = betLevels[0].textContent.trim();
      var leftLevelID = findMacauLevelID(betLevels[0].href);
      //jsdump("homeHref: "+betLevels[0].href+"; homeLevelID: "+leftLevelID);
      var rightLevel = betLevels[1].textContent.trim();
      var rightLevelID = findMacauLevelID(betLevels[1].href);
      //jsdump("awaitHref: "+betLevels[1].href+"; awaitLevelID: "+rightLevelID);
      if (className == "data_row") {
        macauTransOrder[footballIndex].homeGates = leftGates;
        macauTransOrder[footballIndex].homeLevel = leftLevel;
        macauTransOrder[footballIndex].awayGates = rightGates;
        macauTransOrder[footballIndex].awayLevel = rightLevel;
        macauTransOrder[footballIndex].homeLevelID = leftLevelID;
        macauTransOrder[footballIndex].awayLevelID = rightLevelID;
        //添加到LeagueInfo对象中
        macauLeagues[leagueIndex].addTransOrderInfo(macauTransOrder[footballIndex]);
        i++;
      } else {
        macauSizeOrder[footballIndex].homeGates = leftGates;
        macauSizeOrder[footballIndex].homeLevel = leftLevel;
        macauSizeOrder[footballIndex].awayGates = rightGates;
        macauSizeOrder[footballIndex].awayLevel = rightLevel;
        macauSizeOrder[footballIndex].homeLevelID = leftLevelID;
        macauSizeOrder[footballIndex].awayLevelID = rightLevelID;
        macauLeagues[leagueIndex].addSizeOrderInfo(macauTransOrder[footballIndex]);
        //后面有可能没有下一入球，特殊处理，如果有下一入球就加2，没有就加1
        var trNext = rows[i+1];
        var className = trNext.className.trim();
/*        jsdump("trNext.className: "+className+"+"+macauTransOrder[footballIndex].leagueName+"+"+
               macauTransOrder[footballIndex].homeTeam+"+"+
               macauTransOrder[footballIndex].awayTeam);*/
        if(className == "data_row") {
          i += 2;
        } else {
          i ++;
        }
      }
      continue;
    }
//    jsdump("never");
    i++;
  }
//  jsdump("getMacauBodyData: ended");
}

/*
    获取澳门网站的数据 让球盘：trans， 大小盘：size，赔率(水位)：level
*/
function getMacauInfo() {  
  var maindoc = $("macau-browser").contentDocument;  
  try {    
    var frameName = getStringPreference("macau.data.frame", false);    
    var mainFrame = maindoc.getElementsByName("mainFrame")[0].contentDocument;
    var frame = mainFrame.getElementsByName(frameName);    
    var doc = frame[0].contentDocument;
    var tableId = getStringPreference("macau.data.tableid", false);    
    var table = doc.getElementById(tableId);
    var tbody = table.getElementsByTagName("tbody")[0];    
    if (tbody) {
      getMacauBodyData(tbody);
    }
  } catch(e) {
//    jsdump("getMacauInfo: " + e);
  }
}

/*
 获取利记网站的数据 让球盘：trans， 大小盘：size，赔率(水位)：level
*/
function getLijiInfo() {
  //这里是通过分析网站，提取出的ID和name来找到需要解析的Table
//  jsdump("getLijiInfo: started");
  var maindoc = $("liji-browser").contentDocument;
  try {
    var doc = maindoc.getElementById("mainFrame").contentDocument;
    var divTable = doc.getElementById("events");
    var contentTable = divTable.getElementsByClassName("ContentTable")[0];
    var tbodies = contentTable.getElementsByTagName("tbody");
    var i = 0;
    //i=0 表示表头，没有实际数据，所以解析从1开始 is the header not contain league name or data    
    var leagueIndex = -1;
    //比赛索引
    var footballIndex = -1;
    //亚洲让球盘
    lijiTransOrder = [];
    //大小盘
    lijiSizeOrder = [];
    //联盟球队信息
    lijiLeagues = [];
    //保存获取的信息
    //0:联盟信息;1,2:球队名称;3:时间;4:比分;5:盘口;6,7:赔率;8,9:赔率的链接信息(ID)
    for (i = 1; i < tbodies.length; i++) {
      var leagues = tbodies[i].getElementsByClassName("LeagueRow");
      if (leagues.length > 0) { //联盟名称
        leagueIndex += 1;
        var leagueName = leagues[0].textContent.trim();
        lijiLeagues.push(new LeagueInfo(leagueName));
        
      } else { //具体数据
        var rows = tbodies[i].rows;
        if (rows.length == 3) {
          footballIndex += 1;
          //比赛时间 和 比分 score time
          var cells = rows[0].cells;
          var timeElem = cells[0];
          var score = timeElem.childNodes[1].textContent.trim();          
          var time = timeElem.childNodes[3].textContent.trim();
          //var str = "score: " + score + " time: " + time;
          
          //球队名称 team names
          var teamNames = cells[1];
          var leftTeam = teamNames.childNodes[1].textContent.trim();
          var rightTeam = teamNames.childNodes[4].textContent.trim();
          //str = "leftTeam: " + leftTeam + " rightTeam:" + rightTeam;

          //盘口信息 亚洲让球盘盘口和大小盘盘口 (gate)
          var transGate = cells[5].textContent.trim();
          //如果transGate == '';
          if (transGate == '') {
            transGate = rows[1].cells[2].textContent.trim();
          }

          var sizeGate = cells[8].textContent.trim();
          //str = "transGate: " + transGate + ' sizeGate:' + sizeGate;
          //让球盘赔率 data
          var firstTransLevel = cells[6].textContent.trim();
          if (firstTransLevel == '') {
            //没有让球盘信息
            //jsdump("没有让球盘信息");
            
          } else {
            var onclick = cells[6].childNodes[1].getAttribute('onclick');
            var firstTransLevelID = findLevelID(onclick);
            
            var secTransLevel = rows[1].cells[3].textContent.trim();
            onclick = rows[1].cells[3].childNodes[1].getAttribute("onclick");
            var secTransLevelID = findLevelID(onclick);
            
            //让球盘信息
            var transInfos = new OrderInfo();
            transInfos.setParams(lijiLeagues[leagueIndex].name, time, time,
                leftTeam, rightTeam, score, score, transGate,
                transGate, transGate, firstTransLevel, secTransLevel,
                firstTransLevelID, secTransLevelID);
            
            lijiTransOrder.push(transInfos);
            lijiLeagues[leagueIndex].addTransOrderInfo(transInfos);
          }

          //大小盘赔率 size data，比赛中有可能没有大小盘，需要特殊处理
          var firstSizeLevel = cells[10].textContent;
          firstSizeLevel = firstSizeLevel.trim();
          if (firstSizeLevel == '') {
            //表示没有大小盘信息，特殊处理
            //jsdump("没有大小盘信息，进行下一步处理");
            continue;
          } else {
            onclick = cells[10].childNodes[1].getAttribute("onclick");
            var firstSizeLevelID = findLevelID(onclick);
            var secSizeLevel = rows[1].cells[7].textContent;
            secSizeLevel = trimString(secSizeLevel);
            onclick = rows[1].cells[7].childNodes[1].getAttribute("onclick");
            var secSizeLevelID = findLevelID(onclick);
            var sizeInfos = new OrderInfo();
            sizeInfos.setParams(lijiLeagues[leagueIndex].name, time, time,
                leftTeam, rightTeam, score, score, sizeGate,
                sizeGate, sizeGate, firstSizeLevel, secSizeLevel,
                firstSizeLevelID, secSizeLevelID)
        
            lijiSizeOrder.push(sizeInfos);
            lijiLeagues[leagueIndex].addSizeOrderInfo(sizeInfos);            
          }

        }

      }
    }
  } catch(e) {
//    jsdump("getLijiInfo: " + e);
  }
//  jsdump("getLijiInfo: ended");

}

/*
 获取沙巴网站的数据 让球盘：trans， 大小盘：size，赔率(水位)：level
*/
function getShabaInfo() {
//  jsdump("getShabaInfo: started");
  var maindoc = $("shaba-browser").contentDocument;
  try {
    var doc = maindoc.getElementById("mainFrame").contentDocument;    
    var divTable = doc.getElementById("oTableContainer_1");    
    var table = divTable.childNodes[0];    
    var tbody = table.getElementsByTagName("tbody")[0];
    var trs = tbody.rows;    
    var i = 0;
    var leagueIndex = -1;
    var footballIndex = -1;
    //亚洲让球盘
    shabaTransOrder = [];
    //大小盘
    shabaSizeOrder = [];
    //联盟球队信息
    shabaLeagues = [];
    //保存获取的信息
    //0:联盟信息;1,2:球队名称;3:时间;4:比分;5:盘口;6,7:赔率;8,9:赔率的链接信息(ID数值)
    for (i = 0; i < trs.length; i++) {
      var tr = trs[i];

      var leagues = tr.getElementsByClassName("tabtitle");
      if (leagues.length > 0) {
        //联赛名称
        var league = leagues[0].textContent;
        league = trimString(league);
        var strings = league.split('/');
        league = trimString(strings[1]);
        leagueIndex += 1;
        shabaLeagues.push(new LeagueInfo(league));
        
      } else {
        //比赛信息
        //比赛时间和比分 time score
        footballIndex += 1;
        var score = tr.cells[0].childNodes[0].textContent;
        score = trimString(score);
        var time = tr.cells[0].childNodes[2].textContent;
        time = time.trim();
        var str = "score: " + score + " time: " + time;
//        jsdump(str);
        //球队名称 team names
        var firstTeam = tr.cells[1].childNodes[0].textContent;
        firstTeam = trimString(firstTeam);
        var secondTeam = tr.cells[1].childNodes[1].textContent;
        secondTeam = secondTeam.trim();
        str = "firstTeam: " + firstTeam + " secondTeam: " + secondTeam;
//        jsdump(str);

        //亚洲让球盘 盘口和赔率 trans order
        var transGate = tr.cells[3].childNodes[0].textContent;
        transGate = transGate.trim();
        var firstTransLevel = tr.cells[3].childNodes[1].childNodes[0].textContent;
        firstTransLevel = trimString(firstTransLevel);
        //判断是否包含半球，如果有[+1 / +1.5]就拆分开            
        var href = tr.cells[3].childNodes[1].childNodes[0].href;
        var firstTransLevelID = findLevelID(href);

        var secTransLevel = tr.cells[3].childNodes[1].childNodes[2].textContent;
        secTransLevel = secTransLevel.trim();
        href = tr.cells[3].childNodes[1].childNodes[2].href;
        var secTransLevelID = findLevelID(href);
        str = "亚洲盘口：" + transGate + "主场赔率：" + firstTransLevel + "客场赔率：" + secTransLevel;
//        jsdump(str);

        //大小盘盘口和赔率
        var sizeGate = tr.cells[4].childNodes[0].childNodes[0].textContent;
        sizeGate = sizeGate.trim();
        var firstSizeLevel = tr.cells[4].childNodes[1].childNodes[0].textContent;
        firstSizeLevel = firstSizeLevel.trim();
        href = tr.cells[4].childNodes[1].childNodes[0].href;
        var firstSizeLevelID = findLevelID(href);
        var secSizeLevel = tr.cells[4].childNodes[1].childNodes[2].textContent;
        secSizeLevel = secSizeLevel.trim();
        href = tr.cells[4].childNodes[1].childNodes[2].href;
        var secSizeLevelID = findLevelID(href);

        /*
        数组索引说明
        0=league,1=leftTeam,2=rightTeam,3=time,4=score,5=transGate
        6=firstTransLevel,7=secTransLevel,8=firstTransLevelID,9=secTransLevelID
        */
        //让球盘信息
        var transInfos = new OrderInfo();
        transInfos.setParams(shabaLeagues[leagueIndex].name, time, time,
                        firstTeam, secondTeam, score, score, transGate,
                        transGate, transGate, firstTransLevel, secTransLevel,
                        firstTransLevelID, secTransLevelID);
        
        shabaTransOrder.push(transInfos);
        shabaLeagues[leagueIndex].addTransOrderInfo(transInfos);
        
        //大小盘信息
        var sizeInfos = new OrderInfo();
        sizeInfos.setParams(shabaLeagues[leagueIndex].name, time, time,
                        firstTeam, secondTeam, score, score, sizeGate,
                        sizeGate, sizeGate, firstSizeLevel, secSizeLevel,
                        firstSizeLevelID, secSizeLevelID)
        shabaSizeOrder.push(sizeInfos);
        shabaLeagues[leagueIndex].addSizeOrderInfo(sizeInfos);        
      }
    }
  } catch(e) {
//    jsdump("getShabaInfo: " + e);
  }
//  jsdump("getShabaInfo: ended");
}

/*
    获取新球网的数据 让球盘：trans， 大小盘：size，赔率(水位)：level
*/
function getNewballInfo() {
  var maindoc = $("newball-browser").contentDocument;
  try {
    var doc = maindoc.getElementById("fraOdds").contentDocument;
    var div = doc.getElementById("divOddsTableRB");
    var tables = div.getElementsByTagName("table");
    var footTable = null;
    for (var i = 0; i < tables.length; i++) {
      if (tables[i].className == "ot") {
        footTable = tables[i];
        break;
      }
    }
    if (footTable) {
      var tbody = footTable.getElementsByTagName("tbody")[0];
      var rows = tbody.rows;
      if (rows.length <= 5) return;

      var leagueIndex = -1;
      var footballIndex = -1;
      //亚洲让球盘
      newballTransOrder = [];
      //大小盘
      newballSizeOrder = [];
      //联盟球队信息
      newballLeagues = [];
      //保存获取的信息
      //0:联盟信息;1,2:球队名称;3:时间;4:比分;5:盘口;6,7:赔率;8,9:赔率的链接信息(ID数值)
      //找到数据所在位置，后面进行数据的解析
      for (var i = 2; i < rows.length;) {
        if (rows[i].className == 'l') { //leagueName
          leagueIndex += 1;
          var leagueName = rows[i].textContent;
          leagueName = trimString(leagueName);
          newballLeagues.push(new LeagueInfo(leagueName));          
          i++;
          continue;

        } else if (rows[i].className == 'rdl1' || rows[i].className == 'rdl0') {
          //数据
          var cells = rows[i].cells;
          if (cells.length == 16) {
            footballIndex += 1;
            var score = cells[0].childNodes[0].textContent;
            var time = cells[0].childNodes[2].textContent;
            //让球盘
            var firstTeam = cells[1].textContent;
            firstTeam = trimString(firstTeam);

            var transGate = cells[3].textContent;
            transGate = trimString(transGate);
            var firstTransLevel = cells[4].textContent;
            firstTransLevel = trimString(firstTransLevel);
            var firstTransLevelID = cells[4].id;

            //大小盘
            var sizeGate = cells[5].textContent;
            sizeGate = trimString(sizeGate);
            var firstSizeLevel = cells[6].textContent;
            firstSizeLevel = trimString(firstSizeLevel);
            var firstSizeLevelID = cells[6].id;

            var transInfos = new OrderInfo();
            transInfos.setParams(newballLeagues[leagueIndex].name, time, time,
                        firstTeam, '', score, score, transGate,
                        transGate, transGate, firstTransLevel, '',
                        firstTransLevelID, '');
        
            newballTransOrder.push(transInfos);
            newballLeagues[leagueIndex].addTransOrderInfo(transInfos);

            var sizeInfos = new OrderInfo();
            sizeInfos.setParams(newballLeagues[leagueIndex].name, time, time,
                        firstTeam, '', score, score, sizeGate,
                        sizeGate, sizeGate, firstSizeLevel, '',
                        firstSizeLevelID, '')
            newballSizeOrder.push(sizeInfos);
            newballLeagues[leagueIndex].addSizeOrderInfo(sizeInfos);

          } else if (cells.length == 13) { //第二支球队信息
            var secondTeam = cells[0].textContent;
            secondTeam = trimString(secondTeam);
            //transGate
            var transGate = cells[2].textContent;
            transGate = trimString(transGate);
            if (transGate != '') {
              newballTransOrder[footballIndex].gate = transGate;
            }
            transGate = newballTransOrder[footballIndex][5];
            if (transGate.search('/') > -1) {
              var temp = transGate.replace('/', '-');
              newballTransOrder[footballIndex].gate = temp;
            }

            var secTransLevel = cells[3].textContent;
            secTransLevel = trimString(secTransLevel);
            var secTransLevelID = cells[3].id;
            //sizegate
            var sizeGate = cells[4].textContent;
            sizeGate = trimString(sizeGate);
            if (sizeGate != '') {
              newballSizeOrder[footballIndex].gate = sizeGate;
            }
            sizeGate = newballSizeOrder[footballIndex][5];
            if (sizeGate.search('/') > -1) {
              var temp = sizeGate.replace('/', '-');
              newballSizeOrder[footballIndex].gate = temp;
            }

            var secSizeLevel = cells[5].textContent;
            secSizeLevel = trimString(secSizeLevel);
            var secSizeLevelID = cells[5].id;

            newballTransOrder[footballIndex].awayTeam = secondTeam;
            newballTransOrder[footballIndex].awayLevel = secTransLevel;
            newballTransOrder[footballIndex].awayLevelID = secTransLevelID;

            newballSizeOrder[footballIndex].awayTeam = secondTeam;
            newballSizeOrder[footballIndex].awayLevel = secSizeLevel;
            newballSizeOrder[footballIndex].awayLevelID = secSizeLevelID;

          } else if (cells.length == 7) { //进入下一联赛或比赛
            i++;
            continue;
          }
          i++;
          continue;
        }
      }

    }

  } catch(e) {
//    jsdump("getNewballInfo: " + e);
  }
}

function autoLogin() {

}

function logoutWeb() {

}


function refreshWeb() {
  //获取当前的Tab页，如果大于1，并且包含有<browser>，就可以刷新
  var index = $("mainwindow").getAttribute("selectedIndex");
  jsdump("selectedIndex: "+index);
  function reload(browserID) {
    try {
      var browser = $(browserID).contentDocument;
      browser.location.reload();      
    } catch(ex) {
      
    }
  }
  switch(index) {
    case "2": {
      reload("macau-browser");
      break;
    }
    case "3": {
      reload("liji-browser");
      break;
    }
    case "4": {
      reload("shaba-browser");
      break;
    }
    case "5": {
      reload("newball-browser");
      break;
    }
    default: {
      ;
    }
    
  }
}

function gotoHome() {
    //获取当前的Tab页，如果大于1，并且包含有<browser>，就可以刷新
  var index = $("mainwindow").getAttribute("selectedIndex");
  jsdump("selectedIndex: "+index);
  function goHome(browserID) {
    try {
      $(browserID).goHome();      
    } catch(ex) {
      
    }
  }
  switch(index) {
    case "2": {
      goHome("macau-browser");
      break;
    }
    case "3": {
      goHome("liji-browser");
      break;
    }
    case "4": {
      goHome("shaba-browser");
      break;
    }
    case "5": {
      goHome("newball-browser");
      break;
    }
    default: {
      ;
    }    
  }
}

function loginWeb() {

}

function initLevel() {
  /*var listbox = $("list-betinfos");
    var count = listbox.itemCount;
    for(var i=count-1; i>=0; i--) {
        listbox.removeItemAt(i);
    }
    for(var i=0; i<10; i++) {
        var item = document.createElement("listitem");
        var cell_1 = document.createElement("listcell");
        cell_1.setAttribute("label", '亚洲盘');
        var cell_2 = document.createElement("listcell");
        cell_2.setAttribute("label", '0.24');
        var cell_3 = document.createElement("listcell");
        cell_3.setAttribute("label", '2-2.5');
        var cell_4 = document.createElement("listcell");
        cell_4.setAttribute("label", '北京队');
        var cell_5 = document.createElement("listcell");
        cell_5.setAttribute("label", '重庆队');
        item.appendChild(cell_1);
        item.appendChild(cell_2);
        item.appendChild(cell_3);
        item.appendChild(cell_4);
        item.appendChild(cell_5);
        listbox.appendChild(item);
    }*/
}

//controle the toolbar visibility
function toolbarControl(e) {
  var toolbar = $("toolbar-toolbox");
  var checkd = $("mainmenu:view:toolbar").getAttribute("checked");
  toolbar.setAttribute("hidden", !checkd);
}

//control the status panel visibility
function statusPanelControl(e) {
  var statuspanel = $("status-bar");
  var checked = $("mainmenu:view:statuspanel").getAttribute("checked");
  statuspanel.setAttribute("hidden", !checked);
}

//about system
function aboutXulrunner() {
  window.openDialog("chrome://global/content/config.xul");
}

function loadXML(event) {
  domLeagues = loadXMLByName('联赛名称.xml');
  domTeams = loadXMLByName('队名.xml');
  var teamRoot = domTeams.getElementsByTagName('Teams')[0];
  var teams = teamRoot.getElementsByTagName('Team');
//  jsdump("teams:" + teams.length);
  for (var i = 0; i < teams.length; i++) {
    //jsdump(teams[i].textContent);
  }

}

function saveXML(event) {
  saveXMLByName('联赛名称.xml', domLeagues);
  saveXMLByName('队名.xml', domTeams);
}

//about ballbet
function aboutBallbet(e) {
  //getMacauHttprequest();
  //getLijiHttprequest();
  //return;

  //openHelp('ballbet-help', 'chrome://ballbet/help/help.rdf');
  var formFillService = Cc["@mozilla.org/satchel/form-fill-controller;1"].getService(Ci.nsIFormFillController);
  alert(formFillService);
  return;
  var gate = calcBetGate(1, 2, -2, 2);
  alert(gate);
  return;

  var dirservice = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
  var f = dirservice.get('ProfD', Ci.nsILocalFile);

  alert(appInfo);
  alert(appInfo.name);
  alert(appInfo.version);

  //guid
  let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
  let uuid = uuidGenerator.generateUUID();
  //alert(uuid);
  var uuidString = uuid.toString();
  //alert(uuidString);
  //native json
  var nativeJSON = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
  var myObj = {
    "foo": "bar",
    "test": "te"
  };
  //alert(myObj.foo);
  var myJSONString = nativeJSON.encode(myObj);
  //alert(myJSONString);
  var myObj2 = nativeJSON.decode(myJSONString);
  //alert(myObj2.test);
  //fuel
  var application = Cc["@mozilla.org/fuel/application;1"].getService(Ci.fuelIApplication);
  alert(application.id);
  alert(application.name);
  alert(application.version);
  //application.console.open();
  var pre = "app.ballbet.macau.";
  var te = pre + "username";
  alert(te);
  var preName = application.prefs.get(te);
  alert(preName.value);
  alert(preName.type);
  alert(preName.branch);
  application.storage.set("aa", 10);
  var tem = application.storage.get("aa", 4);
  alert(tem);
  //application.restart();
  //window.openDialog("chrome://ballbet/content/about/about.xul", "", "chrome,dialog");
}

//auto update
function updateBallbet(e) {
  var service = Cc['@mozilla.org/updates/update-manager;1'].getService();
  var um = service.QueryInterface(Ci.nsIUpdateManager);
  //var um = getService("@mozilla.org/updates/update-manager;1", "Ci.nsIUpdateManager");
  var up = Cc['@mozilla.org/updates/update-prompt;1'].getService();
  var prompter = up.QueryInterface(Ci.nsIUpdatePrompt);

  if (um.activeUpdate && um.activeUpdate.state == "pending") prompter.showUpdateDownloaded(um.activeUpdate);
  else prompter.checkForUpdates();
}

//extension manager
function addon(e) {
  var winType = "Extension:Manager";
  var url = "chrome://mozapps/content/extensions/extensions.xul"

  if (!e.type && !client.hostCompat.addonManager) e.type = "extensions";

  if (e.type) {
    winType += "-" + e.type;
    url += "?type=" + e.type;
  }

  openWindowByType(winType, url);
}

function openDOMInspector(event) {
  //window.open("chrome://inspector/content/inspector.xul", "_blank", "chrome");
  // Load the Window DataSource so that browser windows opened subsequent to DOM
  // Inspector show up in the DOM Inspector's window list.
  var windowDS = Cc["@mozilla.org/rdf/datasource;1?name=window-mediator"].getService(Ci.nsIWindowDataSource);
  var tmpNameSpace = {};
  var sl = Cc["@mozilla.org/moz/jssubscript-loader;1"].createInstance(Ci.mozIJSSubScriptLoader);
  sl.loadSubScript("chrome://inspector/content/hooks.js", tmpNameSpace);
  tmpNameSpace.inspectDOMDocument(document);

}

function openWindowByType(inType, url, features) {
  var winman = Cc['@mozilla.org/appshell/window-mediator;1'].getService();
  winman = winman.QueryInterface(Ci.nsIWindowMediator);

  var topWindow = winman.getMostRecentWindow(inType);
  var afeature = (features) ? features: "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar";

  if (topWindow) {
    // Requested window is already opened so only focus it
    topWindow.focus();
  } else {
    // Open new instance of requested window
    window.open(url, "_blank", afeature);
  }
}